import { watch, inject, InjectionKey, Ref } from 'vue';

export type CustomInputInjectionValue = {
  customValue: Ref<(() => unknown) | undefined>;
  resetValidation: () => void;
  validateWithTrigger: (trigger: 'onBlur' | 'onChange' | 'onSubmit') => void;
};

export const CUSTOM_INPUT_INJECTION_KEY: InjectionKey<CustomInputInjectionValue> = Symbol(
  'vcu-input'
);

export function useCustomInputValue(customValue: () => unknown) {
  const input = inject(CUSTOM_INPUT_INJECTION_KEY, null);

  if (input && !input.customValue.value) {
    input.customValue.value = customValue;

    watch(customValue, () => {
      input.resetValidation();
      input.validateWithTrigger('onChange');
    });
  }
}
